<template>
  <div class="container">
    <div class="apply">
      <van-cell-group>
       
        <van-field
          v-model="formlist.location"
          required
          label="还车位置"
          placeholder="请选择还车位置"
          readonly
          use-slot
          @click="toMap()"
        >
          <div class="icon-location" slot="right-icon"></div>
        </van-field>
        <van-field v-model="formlist.remarks" label="详细位置" placeholder="请输入具体位置可不填" autosize />
        <van-field
          v-model="formlist.useDate"
          required
          label="还车日期"
          placeholder="请选择用车日期"
          readonly
          @click="handleShowDatePicker"
        />
        <van-field
          v-model="formlist.useTime"
          required
          label="还车时间"
          placeholder="请选择用车时间"
          readonly
          @click="handleShowTimePicker"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="formlist.name" type="text" required label="联系人" placeholder="请输入还车联系人" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="formlist.phone" type="number" required maxlength="11" label="手机号" placeholder="请输入手机号" />
      </van-cell-group>
      <div class="agree">
        <van-radio-group v-bind:value="formlist.isConfirmAgree">
          <van-radio name="0" checked-color="#ad2f2f" @click="onChangeRadio">我已阅读<router-link :to="{path:'/useragreement',query:{id:2}}" class="radio-text">《出险代步车服务协议》</router-link></van-radio>
          
        </van-radio-group>
      </div>
      <div class="btn-container">
        <van-button class="btn-large" @click="submitformlist">申请归还代步车</van-button>
      </div>
      <!--日期选择器-->
      <van-popup v-model="datePicker.isShowDatePicker" position="bottom">
        <van-datetime-picker
          type="date"
          v-model="datePicker.currentDate"
          @cancel="onCloseDatePicker"
          @confirm="onConfirmDatePicker"
          :min-date="datePicker.minDate"
          :max-date="datePicker.maxDate" 
          bind:input="onInput"
        />
      </van-popup>
      <!-- <van-popup v-if="datePicker.isShowDatePicker" position="bottom">
        <div style="width:100px;height:100px;background:red">

        </div>
        <van-datetime-picker type="date" v-model="datePicker.currentDate" bind:input="onInput" />
      </van-popup>-->

      <van-popup v-model="timePicker.isShowTimePicker" position="bottom">
        <van-datetime-picker
          type="time"
          v-model="timePicker.currentTime"
          @cancel="onCloseTimePicker"
          @confirm="onConfirmTimePicker"
          :min-hour="timePicker.minHour"
          :max-hour="timePicker.maxHour"
          :min-minute="timePicker.minMinute"
        />
      </van-popup>
    </div>
  </div>
</template>

<script>
import { formatDate } from "../utils/index.js";
export default {
  components: {},
  data() {
    return {
      radio: "",
      show1: true,
      locationjson:{
        lat:'',
        lnt:'',
      },
      userinfo:{},
      // phone:'',
      formlist: {
        servicecode: "",
        isConfirmAgree: '',
        useDate: "",
        useTime: "",
        location: "",
        carnumber: "",
        framenumber: "",
        reportcase: "",
        errormessage: "",
        remarks: "",
        phone: "",
        cerText: "",
        remark: "",
        name:"",
        position: {
          positionX: "",
          positionY: ""
        },
        
      },
      btnDisabled: true,
      btnLoading: false,
      cer: {
        cerInfo: {
          driverBack: "",
          driverBackInfo: "",
          driverFace: "",
          driverFaceInfo: "",
          idCardBack: "",
          idCardBackInfo: "",
          idCardFace: "",
          idCardFaceInfo: ""
        }
      },
      datePicker: {
        isShowDatePicker: false,
        currentDate: "",
        minDate: new Date(),
        maxDate: ""
      },
      timePicker: {
        isShowTimePicker: false,
        currentTime: "",
        minHour: 9,
        maxHour: 19,
        isToday: false,
        time: "",
        minMinute: "",
        maxMinute: 59
      },
      message: ""
    };
  },
  activated(){
    if(this.$route.query.addr){
      console.log(this.$route.query.addr)
      this.formlist.location=this.$route.query.addr
    }
    if(this.$route.query.latng){
      console.log(this.$route.query.latng)
      let arr = this.$route.query.latng.split(",")
      this.locationjson.lat = arr[0]
      this.locationjson.lng = arr[1]
      console.log(arr)
    }
    if(sessionStorage.getItem('returnremarks')){
          this.formlist.remarks = sessionStorage.getItem('returnremarks')
      }
      if(sessionStorage.getItem('returnuseDate')){
         this.formlist.useDate = sessionStorage.getItem('returnuseDate')
      }
      if(sessionStorage.getItem('returnuseTime')){
          this.formlist.useTime = sessionStorage.getItem('returnuseTime')
      }
      if(sessionStorage.getItem('returnname')){
         this.formlist.name = sessionStorage.getItem('returnname')
      }
      if(sessionStorage.getItem('returphone')){
        this.formlist.phone =sessionStorage.getItem('returphone')
      }
    // if(sessionStorage.getItem("locationjson")){
    //   console.log(sessionStorage.getItem("locationjson"))
    //   this.locationjson = JSON.parse(sessionStorage.getItem("locationjson"));
    //   if(this.locationjson.name&&this.locationjson.address){
    //     this.formlist.location = this.locationjson.name+this.locationjson.address
    //   }else{
    //     this.formlist.location=''
    //   }
    // }
    
    
  },
  created() {
    // alert(1)
    sessionStorage.removeItem("locationjson")
    let userinfos = JSON.parse(sessionStorage.getItem('userinfos'))
    this.userinfo = userinfos
    this.getPickDate();
    let curDate = new Date().getTime();
    let one = 30 * 24 * 3600 * 1000;
    let oneYear = curDate + one;
    console.log(new Date(oneYear));
    this.datePicker.maxDate = new Date(oneYear);
  },
  methods: {
    
    handleShowDatePicker() {
      this.datePicker.isShowDatePicker = true;
      // console.log(this.datePicker.isShowDatePicker)
    },
    handleShowTimePicker() {
      this.$dialog.alert({
          title: '温馨提示',
          message: '申请代步车时间：9:00 - 19:00，申请代步车只可选择距当前时间两个小时以后的可用时间范围',
          confirmButtonText:'知道了',
          confirmButtonColor:'#ad2f2f'
        })
        .then(() => {
          // on confirm
          this.timePicker.isShowTimePicker = true;
        })
    },
    getPickDate() {
      console.log(new Date());
     
    },
    onConfirmDatePicker(e) {
      console.log(e);
      this.formlist.useDate = formatDate(new Date(e));
      this.datePicker.currentDate = new Date(e);
      this.timePicker.currentTime = "";
      this.formlist.useTime = "";
      this.onCloseDatePicker();
      this.getPickHoursData()
      // this.datePicker.isShowDatePicker = false
      // this.timePicker.currentTime = "";
      // this.formlist.useTime = "";
      // this.getPickHoursData();
      // this.onCloseDatePicker();
    },
    getPickHoursData(){
        let minutes = (new Date().getMinutes() / 60).toFixed(2);//当前分钟是不是整点
        let curHours = parseInt(new Date().getHours()) + Number(minutes);//当前小时加分钟
        let minHour = "";
        let maxHour = "";
        if(this.datePicker.currentDate!=""&&this.datePicker.currentDate.getDate() != new Date().getDate()){
          console.log("不是当天")
          minHour = 9;
          maxHour = 19;
          this.timePicker.minHour = minHour;
          this.timePicker.currentTime = "";
          this.formlist.useTime = "";
          this.timePicker.time = this.timePicker.minHour;
          this.timePicker.isToday = false;
          this.updateMinutes();
          return false;
        }
        if(this.datePicker.currentDate == ""){
          minHour = 9;
          maxHour = 19;
          this.timePicker.minHour = minHour;
          this.timePicker.currentTime = "";
          this.formlist.useTime = "";
          this.timePicker.time = this.timePicker.minHour;
          this.timePicker.isToday = false;
          this.updateMinutes();
          return false;
        }
        console.log("当天")
        if(curHours + 2 < 9){ //当前时间+2小时< 9点的时候
          minHour = 9;
          maxHour = 19;
        }else if(curHours + 2 > 19){//当前时间+2小时大于19点的时候
          minHour = 9;
          maxHour = 19
        }else{//当前时间+2小时小于19点大于9点的时候
          minHour = new Date().getHours() + 2;
          maxHour = 19;
        }
        this.timePicker.minMinute = new Date().getMinutes();
        this.timePicker.isToday = true;
        this.timePicker.minHour = minHour;
        this.timePicker.time = this.timePicker.minHour;
        this.timePicker.currentTime = "";
        // this.formlist.useTime = "";
        this.updateMinutes();
      },
      updateMinutes(){
        let _this = this;
        if(_this.timePicker.isToday && _this.timePicker.time == _this.timePicker.minHour ){
          this.timePicker.minMinute = new Date().getMinutes();
          console.log("当天")
        }else{
          this.timePicker.minMinute = 0;
          console.log("不是当前小时")
        }
        var a = this.timePicker.time == "19" ?  0 : 59;
        this.timePicker.maxMinute = a;

      },
    onCloseDatePicker() {
      this.datePicker.isShowDatePicker = false;
    },
    onConfirmTimePicker(e) {
      this.timePicker.currentTime = e;
      this.formlist.useTime = e;
      this.onCloseTimePicker();
    },
    onCloseTimePicker() {
      this.timePicker.isShowTimePicker = false;
    },
    onChangeRadio(e) {
      // let isConfirmAgree = this.formlist.isConfirmAgree;
      this.formlist.isConfirmAgree = this.formlist.isConfirmAgree == "" ? "0" : "";
      console.log(this.formlist.phone)
      console.log(this.formlist.isConfirmAgree)
    },
    onInput(event) {
      this.datePicker.currentDate = event.detail;
    },
    
    toMap(){
      // this.$router.push("/map");
      if(this.formlist.remarks){
          sessionStorage.setItem('returnremarks',this.formlist.remarks)
      }
      if(this.formlist.useDate){
          sessionStorage.setItem('returnuseDate',this.formlist.useDate)
      }
      if(this.formlist.useTime){
          sessionStorage.setItem('returnuseTime',this.formlist.useTime)
      }
      if(this.formlist.name){
          sessionStorage.setItem('returnname',this.formlist.name)
      }
      if(this.formlist.phone){
          sessionStorage.setItem('returphone',this.formlist.phone)
      }
      // https://testcarmng.sshhui.com/gzh/object/public/index.php 测试
      //https://applet.sshhui.com // 正式
      // https://192.168.2.18:8080/
      // http://192.168.2.35:8888/ 后台本地
      
      let url = escape(
        `https://testcarmng.sshhui.com/gzh/object/public/index.php#/returncar?id=${this.$route.query.id}&servicecode=${this.$route.query.servicecode}&regioncode=${this.$route.query.regioncode}`
      )
      // let url = escape(
      //   `http://192.168.2.18:8080/#/returncar?id=${this.$route.query.id}&servicecode=${this.$route.query.servicecode}&regioncode=${this.$route.query.regioncode}`
      // )
      // this.$router.go(-1)
      window.location.href = `https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=${url}&key=JZMBZ-IG6R6-AXOSJ-ENFUL-HKR4K-SKF7K&referer=维代步车`
    },
    changevin(value) {
      this.formlist.framenumber = value;
    },
    
    submitformlist(){
      let _this =this;
      
      if(this.formlist.location == ""){
        this.$toast("请选择用车位置")
        return false;
      }
      if(this.formlist.useDate == ""){
          this.$toast("请选择还车日期");
          return false;
      }
      if(this.formlist.useTime == ""){
        this.$toast("请选择还车时间");
        return false;
      }
      if(this.formlist.phone.length == 0) {
          this.$toast('请输入手机号');
          return false;
      }
      if(!this.phone(this.formlist.phone)) {
        this.$toast('手机号格式不正确');
        return false;
      }
      if(this.formlist.isConfirmAgree==''){
        this.$toast('请阅读并同意代步车出险服务协议');
        return false;
      }
      let params = {
          id:this.$route.query.id,
          regioncode:this.$route.query.regioncode,
          registUserId:this.userinfo.id,
          returnState:'1',
          servicecode:this.$route.query.servicecode,
          position: _this.formlist.location,
          positionX:_this.locationjson.lat,
          positionY:_this.locationjson.lng,
          rdate:_this.formlist.useDate,
          rtime:_this.formlist.useTime,
          rname:_this.formlist.name,
          rphone:_this.formlist.phone,
          remarks:_this.formlist.remarks
        };
        this.$post("/applyvehicle/update", params).then(res => {
          if (res.code == 200) {
            this.$dialog.alert({
              message: '申请成功',
              confirmButtonText:'知道了',
              confirmButtonColor:'#ad2f2f'
            })
            .then(() => {
              // on confirm
              this.$router.push("/order")
            })
          } else {
            this.$dialog.alert({
              message: res.msg,
              confirmButtonText:'知道了',
              confirmButtonColor:'#ad2f2f'
            })
            
          }
        });
        console.log(params)
    },
    //电话号码验证
      phone(data) {
        return !!(/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(data))
      },
  },
  computed: {
    // maxDate(){
    //   let curDate = (new Date()).getTime();
    //   let one = 31 * 24 * 3600 * 1000;
    //   let oneYear = curDate + one;
    //   console.log(new Date(oneYear))
    //   return new Date(oneYear);
    // }
  }
};
</script>

<style lang="scss" scoped>
.apply {
  // padding-top: 15px;
  .icon-location {
    display: inline-block;
    vertical-align: middle;
    background-image: url(../assets/img.png);
    height: 30px;
    width: 22px;
    background-position: 0 2px;
    background-repeat: no-repeat;
    background-size: 90px auto;
  }
  .icon-vin {
    display: inline-block;
    vertical-align: middle;
    background-image: url(../assets/photo.png);
    background-size: 100% 100%;
    height: 22px;
    width: 22px;
  }
  .agree {
    line-height: 20px;
    padding-left: 30px;
    font-size: 14px;
    margin: 20px 0;
    .radio-box {
      display: inline-block;
      vertical-align: middle;
    }
    .radio-text {
      display: inline-block;
      width: 160px;
      vertical-align: middle;
    }
    a {
      text-decoration: none;
      color: #ad2f2f;
    }
  }
  .btn-container {
    padding: 0 20px;
    .van-button {
      color: white !important;
      width: 100%;
      background-color: #ad2f2f;
      height: 40px;
      border-radius: 45px;
    }
  }
}
</style>
